package club.zhilin.guli.service.sms.service.impl;

import club.zhilin.guli.service.base.exception.GlobalException;
import club.zhilin.guli.service.sms.prop.SmsProperties;
import club.zhilin.guli.service.sms.service.ISmsService;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Service;


/**
 * @author zhilin
 * @since 2022/2/24 11:33
 */
@Slf4j
@Service
@EnableConfigurationProperties(SmsProperties.class)
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class SmsServiceImpl implements ISmsService {

    private final SmsProperties smsProperties;

    @Override
    public void send(String phone, String random) {
        DefaultProfile profile = DefaultProfile.getProfile(smsProperties.getRegionId(), smsProperties.getKeyId(), smsProperties.getKeySecret());
        IAcsClient client = new DefaultAcsClient(profile);
        SendSmsRequest request = new SendSmsRequest();
        request.setSignName(smsProperties.getSignName());
        request.setTemplateCode(smsProperties.getTemplateCode());
        request.setPhoneNumbers(phone);
        request.setTemplateParam("{\"code\":\"" + random + "\"}");
        try {
            client.getAcsResponse(request);
        } catch (ClientException e) {
            e.printStackTrace();
            throw new GlobalException(ExceptionUtils.getMessage(e));
        }
    }
}
